//
//  VCForSearch.m
//  PCAForWar
//
//  Created by dllo on 16/2/27.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "VCForSearch.h"
#import "ModelForSearch.h"
#import "NetWorkHandler.h"
#import "VC2ForSearch.h"
#import <DKNightVersion.h>

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height
@interface VCForSearch () <UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,NetWorkHandlerDelegate>

@property (nonatomic, retain) UIView *viewForText;
@property (nonatomic, retain) UITextField *textForSearch;
@property (nonatomic, retain) UIButton *buttonSearch;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) NSString *str;
@property (nonatomic, retain) NSMutableArray *arrForSearch;
@property (nonatomic, retain) NSMutableAttributedString *strAtt;
@property (nonatomic, retain) UIButton *buttonTop;
@property (nonatomic, retain) UIImageView *imageView;

@end

@implementation VCForSearch

- (void)dealloc{
    
    _tableView.dataSource = nil;
    _tableView.delegate = nil;
    _textForSearch.delegate = nil;
    
    [_viewForText release];
    [_textForSearch release];
    [_buttonSearch release];
    [_tableView release];
    [_str release];
    [_arrForSearch release];
    [_strAtt release];
    [_buttonTop release];
    [_imageView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self createNavigation];
    [self createViewForText];
    [self createTextField];
    [self createButton];
    [self createTableView];
    [self createButtonForTop];
    
    self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"WeChat_1457420811.jpeg"]];
    
    self.imageView.frame = self.view.frame;
    
    [self.tableView addSubview:self.imageView];
    
    [_imageView release];
    
}

#pragma mark 夜间模式
- (void)viewDidAppear:(BOOL)animated {
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"夜间模式"]) {
        
        [DKNightVersionManager nightFalling];
        
    } else {
        
        [DKNightVersionManager dawnComing];
    }
    
    self.tableView.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:52 / 256.f green:52 / 256.f blue:52 / 256.f alpha:1]);
    
}

- (void)createNavigation {
    
    self.navigationItem.title = @"搜索";
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor],NSFontAttributeName : [UIFont fontWithName:@"AmericanTypewriter-Bold" size:22],
                                                                       }];
    
    self.navigationController.navigationBar.barTintColor = [UIColor redColor];
    
    self.navigationController.navigationBar.dk_barTintColorPicker = DKColorWithColors([UIColor redColor], [UIColor colorWithRed:39 / 256.f green:39 / 256.f blue:39 / 256.f alpha:1]);
}

- (void)createViewForText {
    
    self.viewForText = [[UIView alloc] initWithFrame:CGRectMake(0, 63, self.view.frame.size.width, 60)];
    
    self.viewForText.backgroundColor = [UIColor lightGrayColor];
    
    [self.view addSubview:self.viewForText];
    
    [_viewForText release];
    
}

- (void)createTextField {
    
    self.textForSearch = [[UITextField alloc] initWithFrame:CGRectMake(20, 20, WIDTH - 100, 35)];
    
    [self.viewForText addSubview:self.textForSearch];
    
    self.textForSearch.backgroundColor = [UIColor whiteColor];
    self.textForSearch.borderStyle = UITextBorderStyleRoundedRect;
    
    self.textForSearch.delegate = self;
    
    self.textForSearch.placeholder = @"请输入搜索内容....";
    
    self.textForSearch.clearButtonMode = UITextFieldViewModeAlways;
    
    [_textForSearch release];
}

- (void)createButton {
    
    self.buttonSearch = [UIButton buttonWithType:UIButtonTypeCustom];
    
    self.buttonSearch.frame = CGRectMake(30 + WIDTH - 120 + 20, 20, 40, 35);
    
    [self.buttonSearch setImage:[UIImage imageNamed:@"sousuo"] forState:UIControlStateNormal];
    
    [self.buttonSearch addTarget:self action:@selector(SearchAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.viewForText addSubview:self.buttonSearch];
    
    [_buttonSearch release];
}

- (void)SearchAction {
    
    [self.textForSearch resignFirstResponder];
    
    if (self.textForSearch.text.length != 0) {
        
        NSString *str1 = @"http://ic.snssdk.com/2/article/v11/search/?keyword=";
        NSString *str2 = self.textForSearch.text;
        NSString *str3 = @"&offset=20&count=20&iid=3754115287&device_id=11707828487&ac=wifi&channel=wandoujia&aid=1097&app_name=news_article&version_code=364&device_platform=android&device_type=Letv%20X500&os_api=21&os_version=5.0.2&uuid=868256022093115&openudid=bbfc8503d59f7c2e&aid=1097";
        
        self.str = [NSString stringWithFormat:@"%@%@%@",str1, str2, str3];
        
        [self handleData];
        
    } else {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"搜索内容不能为空" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *actionDelete = [UIAlertAction actionWithTitle:@"Ok" style:1 handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:actionDelete];
        
        /** 模态推出 */
        [self presentViewController:alert animated:YES completion:^{
            
        }];
        
    }
    
}

#pragma mark 解析数据
- (void)handleData {
    
    self.arrForSearch = [NSMutableArray array];
    
    [NetWorkHandler handlerJSONWithURL:self.str delegate:self];
    
}

#pragma mark 处理解析后的数据
- (void)handlerDidComplete:(id)result {
    
    NSArray *arr11 = @[];
    
    NSArray *arr = [result objectForKey:@"data"];
    
    // 如果搜索的内容没有时
    if ([arr isEqual:arr11]) {
        
        self.imageView.hidden = NO;
        
    } else {
        
        self.imageView.hidden = YES;
        
        for (NSDictionary *dic in arr) {
            
            ModelForSearch *model = [[ModelForSearch alloc] init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [self.arrForSearch addObject:model];
            
            [model release];
        }
        
    }
    
    [self.tableView reloadData];
}

- (void)createTableView {
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 123, WIDTH, HEIGHT - 120 - 49) style:UITableViewStylePlain];
    
    [self.view addSubview:self.tableView];
    
    // 取消横线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"poolForSearch"];
    
    [_tableView release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.arrForSearch.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 判断出现TopButton
    if (indexPath.row == 15) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showButton5" object:nil];
    }
    if (indexPath.row == 5) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"hiddenButton5" object:nil];
    }
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"poolForSearch"];
    
    ModelForSearch *model = [self.arrForSearch objectAtIndex:indexPath.row];
    
    // 关键字高亮
    self.strAtt = [[NSMutableAttributedString alloc] initWithString:model.title];
    
    NSRange range = [model.title rangeOfString:self.textForSearch.text];
    
    cell.textLabel.dk_textColorPicker = DKColorWithColors([UIColor blackColor], [UIColor whiteColor]);
    
    [self.strAtt addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
    
    cell.textLabel.attributedText = self.strAtt;
    
    cell.textLabel.text = model.title;
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    // 夜间模式改变颜色
    cell.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor colorWithRed:52 / 256.f green:52 / 256.f blue:52 / 256.f alpha:1]);
    
    
    [_strAtt release];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    self.hidesBottomBarWhenPushed = YES;
    
    VC2ForSearch *vc2S = [[VC2ForSearch alloc] init];
    
    ModelForSearch *model = [self.arrForSearch objectAtIndex:indexPath.row];
    
    vc2S.groupId = [model.group_id description];
    
    [self.navigationController pushViewController:vc2S animated:YES];
    
    self.hidesBottomBarWhenPushed = NO;
    
    [vc2S release];
}

#pragma mark 点击释放第一响应回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [self.textForSearch resignFirstResponder];
    
    return YES;
    
    
}

#pragma mark 创建Top button
- (void)createButtonForTop {
    
    self.buttonTop = [UIButton buttonWithType:UIButtonTypeSystem];
    
    self.buttonTop.frame = CGRectMake(self.tableView.frame.size.width - 60, self.tableView.frame.size.width + 20, 30, 30);
    
    [self.view addSubview:self.buttonTop];
    
    [self.buttonTop setImage:[UIImage imageNamed:@"Dingbu"] forState:UIControlStateNormal];
    
    self.buttonTop.hidden = YES;
    
    [self.buttonTop addTarget:self action:@selector(TopAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 通知判断出现
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleShowButton) name:@"showButton5" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleButtonclick) name:@"hiddenButton5" object:nil];
}

- (void)handleButtonclick {
    
    self.buttonTop.hidden = YES;
    
}
- (void)handleShowButton {
    
    self.buttonTop.hidden = NO;
    
}

- (void)TopAction:(UIButton *)button {
    
    self.buttonTop.hidden = YES;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
    
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition: UITableViewScrollPositionTop animated:YES];
    
}
















- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
